#include "cg_utils.h"
#include "../basics/error_handle.h"
#include "cg.h"
#include "dirent.h"
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
void get_all_subsystem() {
    char path[MAX_PATH_LENGTH];

    sprintf(path, "%s/cgroup.controllers", ROOT_PATH);

    FILE *file = fopen(path, "r");

    char *buffer = NULL;
    size_t len = 0;
    check(getline(&buffer, &len, file) != -1);

    char *token = strtok(buffer, " ");
    while (token != NULL) {
        token = strtok(NULL, " ");
    }
}

void cgroup_init() {
    if (access(main_path, F_OK) != 0) {
        check(mkdir(main_path, 0755) == 0);
    }

    enable_controller("cpu");
    enable_controller("memory");
    enable_controller("cpuset");
}

void cgroup_exit() {
    if (access(main_path, F_OK) != 0) {
        return;
    }
    DIR *main_path_dir = opendir(main_path);
    struct dirent *diret;

    while ((diret = readdir(main_path_dir)) != NULL) {
        if (diret->d_type == DT_DIR && strcmp(".", diret->d_name) &&
            strcmp("..", diret->d_name)) {
            printf("%s\n", diret->d_name);
            char path[MAX_PATH_LENGTH];
            sprintf(path, "%s/%s", main_path, diret->d_name);
            check(rmdir(path) == 0);
        }
    }

    closedir(main_path_dir);
    rmdir(main_path);
}
